package controllers;

import play.Logger;
import play.libs.Akka;
import play.mvc.*;
import akka.actor.ActorRef;
import akka.actor.Props;

import com.fasterxml.jackson.databind.JsonNode; 

import views.html.*;
import models.*;
import models.msgs.Info;

public class Application extends Controller {
  
    static ActorRef tableActor;
    static int start;
    
    
    public static Result index() {
        if (tableActor == null)
            return ok(indexFirst.render());
        else {
            if( Table.isPlaceForPlayer())
        	return ok(index.render());
            else {
        	flash("error", "We have sufficient number of players.");
        	return ok(indexError.render());
            }
        }
    }
  
    public static Result joinGame(String username) {
	if(username == null || username.trim().equals("")) {
            flash("error", "Please choose a valid username.");
            return redirect(routes.Application.index());
        }
	else if( Table.isNameUsed(username)) {
	    flash("error", "This name is used. Please choose another username.");
            return redirect(routes.Application.index());
	}
	return ok(chatRoom.render(username));
    }
    
    public static Result action(String action) {
	return ok(index.render());
    }

    public static Result chatRoomJs(String username) {
        return ok(views.js.chatRoom.render(username));
    }
    
    public static Result createTable(String numberOfPlayers, String startingCoins, String smallBlind, String bigBlind, String username) {
	try {
	    int numOfPlayers = Integer.parseInt(numberOfPlayers);
	    int startCoins = Integer.parseInt(startingCoins);
	    int sBlind = Integer.parseInt(smallBlind);
	    int bBlind = Integer.parseInt(bigBlind);
	    tableActor = Akka.system().actorOf(Props.create(Table.class, numOfPlayers, startCoins, sBlind, bBlind));
	    start = startCoins;
	    return redirect(routes.Application.joinGame(username));
	    //return ok(chatRoom.render(username));
	    
	} catch (NumberFormatException e) { 
	    flash("error", "Please choose a valid number of starting coins, big and small blind.");
            return ok(indexFirst.render());
	}
	
    }
    /**
     * Handle the chat websocket.
     */
    public static WebSocket<JsonNode> chat(final String username) {
        return new WebSocket<JsonNode>() {
            
            // Called when the Websocket Handshake is done.
            public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){
                
            	//Table.notifyAll(new Info("I've got a WebSocket", username));
            	
                // Join the chat room.
                try {                	
                	Table.join(username, in, out);
                	
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
    }
  
}
